package com.woniu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

/**
 * JWT工具类
 *
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/9/5 19:40
 */
public class JWTUtils {
    private static final String SECURITY = "WONIU";
    //默认过期时间  单位毫秒 30分钟
    private static final long EXPIRES = 30 * 1000 * 60;

    //方法一；生成token
    public static String sign(String username, String password) {
        long extime = System.currentTimeMillis() + EXPIRES;
        return JWT.create().withClaim("username", username)
                .withExpiresAt(new Date(extime))
                //签名的加密算法
                .sign(Algorithm.HMAC256(username + password + SECURITY));
    }

    //方法二: 获取用户名  根据生成时的name值进行获取
    public static String getUsername(String token) {
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }

    //方法三，返回校验的结果
    public static boolean verify(String token, String username, String password) {
        //通过JWT工具类底层，帮你生成新的token，来判断之前的token有没有被篡改
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(username + password + SECURITY)).withClaim("username", username).build();
        jwtVerifier.verify(token);
        //如果不报错，说明校验成功。直接返回true
        return true;
    }

}
